package com.se.db;

import com.se.common.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import static com.se.common.Constant.GET_SQL_CONNECTION_FAILED;
import static com.se.common.Constant.USERNAME;

/**
 * 用户数据操作类（单例模式） - 提供用户表的CRUD操作
 */
public class DbUser {
    private static volatile DbUser instance;
    private static final Logger logger = LoggerFactory.getLogger(DbUser.class);

    private DbUser(){
    }

    public static DbUser getInstance() {
        if(instance == null) {
            synchronized (DbUser.class) {
                if(instance == null) {
                    instance = new DbUser();
                }
            }
        }
        return instance;
    }

    /**
     * 添加用户
     * @param user 用户对象
     */
    public void add(User user) throws SQLException {
        Connection conn = DbUtils.getConnection();
        PreparedStatement ps = null;
        String sql = "INSERT INTO user(username,password,notifyList) VALUES(?,?,?)";

        if(conn == null){
            throw new SQLException(GET_SQL_CONNECTION_FAILED);
        }
        ps = conn.prepareStatement(sql);
        ps.setString(1, user.getUserName());
        ps.setString(2, user.getPassword());
        ps.setString(3, user.getStringNotifyList());
        ps.executeUpdate();
        DbUtils.close(ps, conn);
    }

    /**
     * 更新用户信息
     * @param user 新用户信息
     * @param userName 原用户名（作为查询条件）
     */
    public void update(User user, String userName) throws SQLException {
        Connection conn = DbUtils.getConnection();
        PreparedStatement ps = null;
        String sql = "UPDATE user SET username=?,notifyList=? WHERE username=?";
        if(conn == null){
            throw new SQLException("连接获取失败");
        }

        ps = conn.prepareStatement(sql);
        ps.setString(1, user.getUserName());
        ps.setString(2,user.getStringNotifyList());
        ps.setString(3,userName);
        ps.executeUpdate();
        DbUtils.close(ps, conn);
        logger.info("更新了用户信息: {}", user.getUserName());
    }

    /**
     * 获取用户信息
     * @param userName 用户名
     * @return 用户对象（未找到返回null）
     */
    public User getUser(String userName) throws SQLException {
        Connection conn = DbUtils.getConnection();
        PreparedStatement ps = null;
        String sql = "SELECT username,password,notifyList FROM user WHERE username = ?";
        if(conn == null){
            throw new SQLException(GET_SQL_CONNECTION_FAILED);
        }
        ps = conn.prepareStatement(sql);
        ps.setString(1,userName);
        ResultSet rs = ps.executeQuery();
        User user = null;
        if(rs.next()) {
            user = new User(rs.getString(1), rs.getString(2));
            user.setNotifyList(rs.getString(3));
        }
        DbUtils.close(ps, rs, conn);
        return user;
    }

    public List<User> getAllUser() throws SQLException{
        String sql = "SELECT username,notifyList FROM user";
        Connection conn = DbUtils.getConnection();
        List<User> users = new ArrayList<>();

        if(conn == null) {
            throw new SQLException(GET_SQL_CONNECTION_FAILED);
        }

        try(PreparedStatement ps = conn.prepareStatement(sql)) {

            try(ResultSet rs = ps.executeQuery()) {
                while(rs.next()) {
                    User user = new User();
                    user.setUserName(rs.getString(USERNAME));
                    user.setNotifyList(rs.getString("notifylist"));
                    users.add(user);
                }
            }
        }
        DbUtils.close(conn);
        return users;
    }

    public List<User> search(String keyword) throws SQLException {
        String sql = "SELECT username,password,notifyList FROM user WHERE username like ?";
        Connection conn = DbUtils.getConnection();

        if(conn == null) {
            throw new SQLException(GET_SQL_CONNECTION_FAILED);
        }

        List<User> re = new ArrayList<>();
        try(PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, '%' + keyword + '%');
            ResultSet rs = ps.executeQuery();
            while(rs.next()) {
                re.add(new User(rs.getString(1), null));
            }
        }

        DbUtils.close(conn);
        return re;
    }


    /**
     * 删除用户
     * @param username 要删除的用户名
     */
    public void delete(String username) throws SQLException {
        Connection conn = DbUtils.getConnection();
        PreparedStatement ps = null;
        String sql = "DELETE FROM user WHERE username = ?";
        if(conn == null){
            throw new SQLException(GET_SQL_CONNECTION_FAILED);
        }
        ps = conn.prepareStatement(sql);
        ps.setString(1, username);
        ps.executeUpdate();
        DbUtils.close(ps, conn);
    }
}
